<?php
declare (strict_types=1);
// +----------------------------------------------------------------------
// | 用户中心
// +----------------------------------------------------------------------

namespace app\home\controller;

use app\common\model\Article;
use app\common\model\Config;
use app\common\model\Payment;
use app\common\model\Project;
use app\common\model\ProjectIssue;
use app\common\model\User;
use app\common\model\UserBalanceLog;
use app\common\model\VerificationCode;
use app\common\service\UserService;
use helper\ali\Ocr;
use helper\util\Str;
use think\facade\View;

class UserController extends HomeBaseController
{
    // 用户中心首页
    public function index()
    {
        $view = [
            'user' => (array)auth()->user(),
        ];
        View::assign($view);
        return View::fetch('user/index');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return string
     */
    public function read($id)
    {
        $view = [
            'user'     => auth()->retrieveById($id),
            'articles' => Article::where('user_id',$id)->order('id desc')->limit(5)->select(),
            'comments' => auth()->retrieveById($id),
        ];
        View::assign($view);
        return View::fetch('user/info');
    }

    /**
     * 工单
     */
    public function issue()
    {
        if ($this->request->isAjax()) {
            $list = ProjectIssue::with('project')
                ->where('user_id', $this->user_id)
                ->order('id', 'desc')
                ->paginate(10);
            $count = $list->total();
            $list  = $list->items();
            $this->result($list,'获取成功', ['count' => $count]);
        }
        $projects = Project::select();
        View::assign('projects', $projects);
        return View::fetch('user/issue');
    }

    /**
     * 提交工单
     * @return \think\Response
     */
    public function doIssue()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->user_id;
        ProjectIssue::create($data);
        return $this->success('操作成功');
    }

    /**
     * 发帖管理
     * @return string
     */
    public function article()
    {
        $user = (array)auth()->user();
        $view = [
            'user'      => $user,
        ];
        View::assign($view);
        return View::fetch('user/article');
    }

    /**
     * 发帖
     */
    public function post()
    {
        $user_id = auth()->id();
        $list = Article::where('user_id', $user_id)->order('id desc')->paginate(10);
        if ($list->isEmpty()) {
            $data = [
                'code'    => 1,
                'message' => '数据为空',
            ];
            return json($data);
        }
        $data = [
            'code'    => 0,
            'message' => '请求成功',
            'count'   => $list->total(),
            'data'    => $list->items()
        ];
        return json($data);
    }

    /**
     * 收藏
     */
    public function favorite()
    {
        $data = [
            'code'    => 0,
            'message' => '数据为空',
            'count'   => 0,
            'data'    => []
        ];
        return json($data);
    }

    // 用户中心设置页
    public function set()
    {
        $view = [
            'user' => (array)auth()->user(),
        ];
        View::assign($view);
        return View::fetch('user/set');
    }

    public function message()
    {
        return View::fetch('user/message');
    }

    /**
     * @OA\Get(path="/user/profile",tags={"用户"},summary="查询",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="mobile", in="query", description="手机", @OA\Schema(type="string")),
     *   @OA\Parameter(name="union_id", in="query", description="唯一ID", @OA\Schema(type="string")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function search()
    {
        $param = $this->request->param();
        $where = [];
        if (isset($param['mobile'])) {
            $where[] = ['mobile', '=', $param['mobile']];
        }
        if (isset($param['union_id'])) {
            $where[] = ['id', '=', Str::decrypt($param['union_id'], 'mei')];
        }
        $fieldStr = 'name,mobile';
        if (empty($field)) {
            $user= User::field($fieldStr)->where($where)->find();
        } else {
            $fieldArr     = explode(',', $fieldStr);
            $postFieldArr = explode(',', $field);
            $mixedField   = array_intersect($fieldArr, $postFieldArr);
            if (empty($mixedField)) {
                $this->error('您查询的信息不存在！');
            }
            $fieldStr = implode(',', $mixedField);
            if (count($mixedField) > 1) {
                $user = User::field($fieldStr)->where($where)->find();
            } else {
                $user = User::where($where)->value($fieldStr);
            }
        }
        if (!$user) {
            $this->error('获取失败');
        }
        $this->success('获取成功', $user);
    }

    /**
     * 修改资料
     */
    public function setInfo()
    {
        $param = $this->request->param;
        $data['sex'] = $param['sex'];
        $data['qq'] = input("post.qq");
        $data['mobile'] = input("post.mobile");
        if ($data['mobile']) {
            //不可和其他用户的一致
            $id = User::where('mobile', $data['mobile'])
                ->where('id', '<>', session('user.id'))
                ->find();
            if ($id) {
                $this->error('手机号已存在');
            }
        }

        //更新信息
        User::where('id', session('user.id'))->update($data);
        $this->success('修改成功');
    }

    /**
     * @OA\Put(path="/user/auth",tags={"用户"},summary="实名",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="姓名", property="name", type="integer"),
     *           @OA\Property(description="身份证号码", property="id_card", type="number"),
     *           @OA\Property(description="身份证照片", property="id_card_image", type="json"),
     *           required={"name","id_card","id_card_image"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function authentication()
    {
        $post       = $this->request->param();
        $post['id'] = $this->user_id;
        $this->validate($post, 'app\common\validate\UserCard');
        $res = UserService::authentication($post);
        if (!$res) {
            $this->error("认证失败");
        }
        $this->success('认证成功');
    }

    /**
     * @OA\Put(path="/user/mobile",tags={"用户"},summary="手机",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="手机", property="mobile", type="number"),
     *           @OA\Property(description="验证码", property="code", type="number"),
     *           required={"mobile","code"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function mobile()
    {
        $param   = $this->request->param();
        $param['id'] = $this->user_id;
        $rule = [
            'mobile|手机'  => 'require|mobile',
            'code|验证码'  => 'require|number',
        ];
        $this->validate($param, $rule);

        if ($param['code'] != VerificationCode::getCode($param['mobile'])) {
            $this->error('验证码错误');
        }

        $data = User::update(['id' => $param['id'], 'mobile' => $param['mobile']]);
        if (!$data) {
            $this->error("保存失败");
        }
        $this->success('保存成功');
    }

    /**
     * @OA\Get(path="/user/qrcode",tags={"用户"},summary="二维码",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function qrcode()
    {
        //$code   = Str::encrypt($this->user_id, 'mei');
        //$qrCode = new QrCode("https://m.meinongwang.com.cn/#/pages/user/qrcode/bind?union_id=" . $code);
        //$qrCode->disableBorder();
        //$output  = new Output\Png();
        //$content = $output->output($qrCode, 200, [255, 255, 255], [0, 0, 0]);
        //$this->success('获取成功', ['image' => 'data:image/png;base64,' . base64_encode($content), 'union_id' => $code]);
    }

    /**
     * 充值记录
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function recharge()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['user_id'] = $this->user_id;
            $param['type'] = 1;
            $list = UserBalanceLog::getList($param);
            $this->result([],'获取成功', $list);
        }
        View::assign('payment', $this->payment(['is_recharge'=>1]));
        return View::fetch('user/recharge');
    }

    /**
     * 充值
     */
    public function doRecharge()
    {
        $param = $this->request->param();
        $amount = (float) $param['amount'];

        $return_url = $this->website['domain'] . '/user/tips';
        $out_trade_no = date('YmdHis') . random_int(1000,9999);
        switch ($param['payment']) {
            case 4:
                $pay = Payment::alipay();
                break;
            case 5:
                $pay = Payment::wxpay();
                break;
            case 6:
                $pay = Payment::qpay();
                break;
            case 7:
                $pay = Payment::unionpay();
                break;
            case 8:
                $pay = Payment::jdunipay();
                break;
            default :
                $pay = null;
        }
        $pay->page('充值', $out_trade_no, $amount, $return_url);
    }

    /**
     * 充值结果
     * @return string
     */
    public function tips()
    {
        $this->auth()->syncUser();
        return View::fetch('template/tips');
    }

    /**
     * @OA\Get(path="/withdraw",tags={"提现"},summary="提现记录",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Parameter(name="type", in="query", description="类型:0充值1提现", @OA\Schema(type="int")),
     *   @OA\Parameter(name="create_time", in="query", description="时间", @OA\Schema(type="datetime")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function transfer()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['user_id'] = $this->user_id;
            $param['type'] = 2;
            $list = UserBalanceLog::getList($param);
            $this->result([], '获取成功', $list);
        }
        View::assign('payment', $this->payment(['is_transfer'=>1]));
        return View::fetch('user/transfer');
    }

    /**
     * @OA\Post(path="/withdraw",tags={"提现"},summary="申请提现",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="支付方式:4支付宝5微信", property="payment", type="integer"),
     *           @OA\Property(description="金额", property="amount", type="numbeer"),
     *           required={"payment","amount"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function doTransfer()
    {
        $param   = $this->request->param();
        $user_id = $this->user_id;

        // 1.验证数据
        // 1.1 数据验证
        $this->validate($param, 'app\common\validate\Transfer');

        // 1.2 联表验证
        if ($param['amount'] > $this->user->balance) {
            $this->error("余额不足");
        }
        // 1.2.1 验证账号
        //$oauth = Oauth::getAccount($user_id);
        //if ($param['payment'] == 4) {
        //    if (!isset($oauth['alipay'])) {
        //        $this->error("未绑定支付宝账号");
        //    }
        //    $account = "支付宝（{$oauth['alipay']}）";
        //} else {
        //    if (!isset($oauth['wechat'])) {
        //        $this->error("未绑定微信账号");
        //    }
        //    $account = "微信（{$oauth['wechat']}）";
        //}
        // 1.2.2 提现设置
        $config = Config::config('transfer');
        if ($param['amount'] < $config['min'] || $param['amount'] > $config['max']) {
            $this->error('最低提现金额不小于' . $config['min'] . '元');
        }
        $count = UserBalanceLog::where('type', 1)->whereDay('create_time')->count();
        if ($count > $config['count']) {
            $this->error('每日提现次数不超过' . $config['count'] . '次');
        }

        // 3.调用支付
        $fee = $config['rate'] > 0 ? round($param['amount'] * $config['rate'], 2) : 0;
        $amount = round($param['amount'] - $fee, 2);
        $trade_no = date('YmdHis') . random_int(1000,9999);
        $result = Payment::transfer($user_id, $param['payment'], $fee, $trade_no, $amount, $param['account'], $param['name'], $param['user_note']);
        if ($result) {
            $this->success('转账成功');
        }
        $this->error('转账失败');
    }
}